package com.ymatou.iapi.productquery.testcase;

import com.google.common.reflect.TypeToken;
import com.mongodb.BasicDBObject;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productquery.parameter.ActivityCatalogInfo;
import com.ymatou.iapi.productquery.parameter.ActivityProducts;
import com.ymatou.iapi.productquery.parameter.GetNewestProductListBySellerIdAndDateBean;
import com.ymatou.iapi.productquery.parameter.ProductInListDto;
import com.ymatou.iapi.productquery.service.GetNewestProductListBySellerIdAndDateCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P2;
import com.ymttest.business.service.LiveRoomCallService;
import com.ymttest.business.service.ProductManagerCallServiceV3;
import com.ymttest.database.model.LiveRoom;
import com.ymttest.database.mongo.jproduct.ProductsWapperV2;
import com.ymttest.utils.YMTDateUtil;
import org.junit.*;
import org.junit.experimental.categories.Category;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
*指定日期的买手新品列表
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_GetNewestProductListBySellerIdAndDate{
	private static GetNewestProductListBySellerIdAndDateBean getnewestproductlistbyselleridanddateBean;
	private static GetNewestProductListBySellerIdAndDateCall getnewestproductlistbyselleridanddateCall;
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("指定日期的买手新品列表");
	}

	@Before
	public void caseUp() {
		getnewestproductlistbyselleridanddateBean=new GetNewestProductListBySellerIdAndDateBean();
		getnewestproductlistbyselleridanddateCall=new GetNewestProductListBySellerIdAndDateCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getnewestproductlistbyselleridanddateCall.getOpurl());
	}
	private void verifyDB() throws Exception {
		ArrayList<ProductInListDto> productList = getnewestproductlistbyselleridanddateCall.getProductList();
		//查询当前时间在 start到end+7 的新商品 按新品时间倒序
		ProductsWapperV2 ProductsWapper = new ProductsWapperV2();
		if (productList != null && productList.size() != 0) {
			BasicDBObject search = new BasicDBObject();
			search.append("sid", getnewestproductlistbyselleridanddateBean.getSellerId());
			search.append("isnew", true);
//			.field("newstart").lessThanOrEq(now)
//            .field("newend").greaterThanOrEq(now)
			Date d1 = YMTDateUtil.getDate(getnewestproductlistbyselleridanddateBean.getDate(),"yyyy-MM-dd");
			Date d2=YMTDateUtil.getBeforeOrNextDate(d1, 1);
			
			
			search.append("newstart", new BasicDBObject("$lte", new Date()));
			search.append("newend", new BasicDBObject("$gte", YMTDateUtil.getBeforeOrNextDate(new Date(), -7)));
			
			BasicDBObject search1=new BasicDBObject("newstart", new BasicDBObject("$lte",d2));
			BasicDBObject search2=new BasicDBObject("newstart", new BasicDBObject("$gte", d1));
			BasicDBObject andObj = new BasicDBObject("$and",Arrays.asList(search,search1,search2));
			BasicDBObject orderBy = new BasicDBObject("newstart", -1);
			Logger.debug("search:"+andObj.toString());
			List<Map> dlist = ProductsWapper.selectProduct(andObj, orderBy);

//			Logger.verifyEquals(dlist.size(), getnewestproductlistbyselleridanddateCall.getJsonObject().get("Data").getAsJsonObject().get("Count").getAsInt(), "验证Count");
			System.out.println(dlist);
			System.out.println(FormatUtil.beanToGSONString(productList));
			for (int i = 0; i < productList.size(); i++) {
				ProductInListDto preutrn = productList.get(i);
				Map pdb = dlist.get(i);
				Logger.comment("验证商品:" + preutrn.getProductId());
				Logger.verifyEquals(preutrn.getProdId(), pdb.get("ipid").toString(), "验证ipid");
				Logger.verifyEquals(preutrn.getProductId(), pdb.get("spid").toString(), "验证spid");
				Logger.verifyEquals(preutrn.getTitle(), pdb.get("title"), "验证title");
				Logger.verifyEquals(preutrn.getMainPic(), ((List) pdb.get("pics")).get(0), "验证MainPic");
				Logger.verifyEquals(preutrn.getValidStart(), YMTDateUtil.getDate(pdb.get("start").toString(), YMTDateUtil.YMDGMT, Locale.US), "验证start");
				Logger.verifyEquals(preutrn.getValidEnd(), YMTDateUtil.getDate(pdb.get("end").toString(), YMTDateUtil.YMDGMT, Locale.US), "验证end");
				Logger.verifyEquals(preutrn.getMinPrice().toString(), pdb.get("minp").toString().split(",")[0].toString(), "验证minp");
				Logger.verifyEquals(preutrn.getMaxPrice().toString(), pdb.get("maxp").toString().split(",")[0].toString(), "验证maxp");
				Logger.verifyEquals(preutrn.getSellerId(), pdb.get("sid"), "验证sid");
				Logger.verifyEquals(preutrn.getSellerName(), pdb.get("sname"), "验证sname");
				Logger.verifyEquals(preutrn.getCountryId(), pdb.get("country"), "验证country");
				Logger.verifyEquals(preutrn.getIsPspProduct(), pdb.get("ispsp"), "验证ispsp");

				// 待确认这个逻辑 由于目前改成newend+7天 可能出现不在start到end之间的数据此时返回false
				// 这里按照原来的逻辑计算
				search = new BasicDBObject();
				search.append("sid", getnewestproductlistbyselleridanddateBean.getSellerId());
				search.append("isnew", true);
				search.append("newstart", new BasicDBObject("$lte", new Date()));
				search.append("newend", new BasicDBObject("$gte", new Date()));
				 search1=new BasicDBObject("newstart", new BasicDBObject("$lte",d2));
				 search2=new BasicDBObject("newstart", new BasicDBObject("$gte", d1));
				 andObj = new BasicDBObject("$and",Arrays.asList(search,search1,search2));
				search.append("spid", preutrn.getProductId());
				orderBy = new BasicDBObject("newstart", -1);
				List<Map> isnewm = ProductsWapper.selectProduct(andObj, orderBy);
				// Logger.debug("真正的新品:"+isnewm);
				Logger.verifyEquals(preutrn.getIsNewProduct(), (boolean) pdb.get("isnew") == true && isnewm.size() == 1, "验证isnew");
				//
				Logger.verifyEquals(preutrn.getTariffType(), Double.valueOf(pdb.get("tariffy").toString()).intValue(), "验证是否包税");
				Logger.verifyEquals(preutrn.getDeliveryMethod(), pdb.get("deliv"), "验证发货方式");
				Logger.verifyEquals(preutrn.getIsHotRecmd(), pdb.get("istop"), "验证热推");
				Logger.verifyEquals(preutrn.getOwnProduct() == true ? 1 : 0, pdb.get("own"), "验证直营商品");
				// 免税/包邮
				// 包邮默认true
				//有templates运费模板并且tlid 模板id大于0 不包邮
				if(pdb.get("templates")!=null&&((List<Map>)pdb.get("templates")).size()>0){
					if(((List<Map>)pdb.get("templates")).stream().filter(map->{return (int)map.get("tlid")>0;}).count()>0){
						Logger.verifyEquals(preutrn.getIsFreeShipping(), false, "验证是否包邮");
					}else{
						Logger.verifyEquals(preutrn.getIsFreeShipping(), true, "验证是否包邮");
					}
					
				}else{
					Logger.verifyEquals(preutrn.getIsFreeShipping(), true, "验证是否包邮");
				}
				Logger.verifyEquals(preutrn.getNewStartTime(), YMTDateUtil.getDate(pdb.get("newstart").toString(), YMTDateUtil.YMDGMT, Locale.US), "验证newstart");
				Logger.verifyEquals(preutrn.getNewEndTime(), YMTDateUtil.getDate(pdb.get("newend").toString(), YMTDateUtil.YMDGMT, Locale.US), "验证newend");
				search = new BasicDBObject();
				search.append("spid", getnewestproductlistbyselleridanddateBean.getSellerId());
				// 验证规格相关
				List<Map> clist = ProductsWapper.selectCatalogs(search, null);
				// 库存有2种算法
				Integer stock = 0;
				if (clist != null && clist.size() > 0) {
					Boolean haspresale = false;
					Boolean allpresale = true;
					for (int ci = 0; ci < clist.size(); ci++) {
						Map mcatalog = clist.get(ci);
						boolean presale = (boolean) mcatalog.get("presale");
						stock += Integer.valueOf(mcatalog.get("stock").toString());
						if (presale) {
							haspresale = true;
							allpresale = allpresale & presale;
						}
					}
					Logger.verifyEquals(preutrn.getIsAnyPreSale(), haspresale, "验证有预售");
					Logger.verifyEquals(preutrn.getIsAllPreSale(), allpresale, "验证全部预售");
				}
				// 规格end
				// 查询活动数据
				search = new BasicDBObject();
				search.append("spid", getnewestproductlistbyselleridanddateBean.getSellerId());
				search.append("start", new BasicDBObject("$lte", new Date()));
				search.append("end", new BasicDBObject("$gte", new Date()));
				List<Map> alist = ProductsWapper.selectActivityProducts(search, null);
				if (alist != null && alist.size() > 0) {
					Logger.debug("alist:" + alist);
					List<ActivityProducts> ActivityCatalogInfoList = (List<ActivityProducts>) FormatUtil.GSONToObject(alist.toString(), new TypeToken<List<ActivityProducts>>() {
					}.getType());
					// 查出来的活动数据中是否有有效的,有效则库存为活动库存 无效则是所有规格库存
					Integer aaid = ActivityCatalogInfoList.stream().collect(Collectors.summingInt(ActivityProducts::getActivityId));
					if (aaid > 0) {
						int activityStock = ActivityCatalogInfoList.get(0).getCatalogs().stream().collect(Collectors.summingInt(ActivityCatalogInfo::getActivityStock));
						Logger.verifyEquals(new BigDecimal( preutrn.getActivityMarketPrice()).setScale(2),new BigDecimal(ActivityCatalogInfoList.get(0).getMarketPrice()).setScale(2), "验证MarketPrice");
						Logger.verifyEquals(preutrn.getStock(), activityStock, "验证全部预售");
					} else {
						Logger.verifyEquals(preutrn.getStock(), stock, "验证stock");
					}

				}
			}

		}

	}
	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_GetNewestProductListBySellerIdAndDate_001() {
		Logger.start(true,"获取买手新商品列表成功");
		try {
			int sellerid = 288484;
			getnewestproductlistbyselleridanddateBean.setSellerId(sellerid);
			//这个时间指的是
			getnewestproductlistbyselleridanddateBean.setDate("2018-06-21");
			getnewestproductlistbyselleridanddateCall.setData(getnewestproductlistbyselleridanddateBean);
			getnewestproductlistbyselleridanddateCall.callService();			
			Logger.verifyEquals("200", getnewestproductlistbyselleridanddateCall.getString("Code"), "返回Code");
			Logger.verifyEquals("200", getnewestproductlistbyselleridanddateCall.getString("BCode"), "返回BCode");
			// GetProductListBySellerIdRespData
			verifyDB();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_GetNewestProductListBySellerIdAndDate_002() {
		Logger.start(true,"不输入date失败");
		try {
			int sellerid = 288484;

			getnewestproductlistbyselleridanddateBean.setSellerId(sellerid);
			//这个时间指的是
//			getnewestproductlistbyselleridanddateBean.setDate("2019-05-27");
			getnewestproductlistbyselleridanddateCall.setData(getnewestproductlistbyselleridanddateBean);
			getnewestproductlistbyselleridanddateCall.callService();			
			Logger.verifyEquals("201", getnewestproductlistbyselleridanddateCall.getString("Code"), "返回Code");
			Logger.verifyEquals("-2", getnewestproductlistbyselleridanddateCall.getString("BCode"), "返回BCode");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P2.class})
	@TestCase
	@Ignore
	public void Tc_GetNewestProductListBySellerIdAndDate_003() {
		Logger.start(true,"排除直播快速发布商品(与Tc_GetNewProductListBySellerIdList_003问题一样)");
		try {
			int sellerid = 288484;
			LiveRoom createlive = LiveRoomCallService.CreateSellerLive(LiveRoomCallService.initCreatesellerliveBean(sellerid));
			LiveRoomCallService.UpdateLiveTimeToStart(createlive.getId());
			LiveRoomCallService.SellerLiveOnline(createlive.getId(), createlive.getUserId());

			AddSellerProductRequest addProdReq = ProductManagerCallServiceV3.initAddSellerProductRequest(sellerid);
			addProdReq.getProduct().setLiveRoomId(createlive.getId());
			String productId = ProductManagerCallServiceV3.AddSellerProduct(addProdReq);
			getnewestproductlistbyselleridanddateBean.setSellerId(sellerid);
			//这个时间指的是
			String formatTime = YMTDateUtil.getFormatTime(new Date(), "yyyy-MM-dd");
			getnewestproductlistbyselleridanddateBean.setDate(formatTime);
			getnewestproductlistbyselleridanddateCall.setData(getnewestproductlistbyselleridanddateBean);
			getnewestproductlistbyselleridanddateCall.callService();
			Logger.verifyEquals("200", getnewestproductlistbyselleridanddateCall.getString("Code"), "返回Code");
			Logger.verifyEquals("200", getnewestproductlistbyselleridanddateCall.getString("BCode"), "返回BCode");
			ArrayList<ProductInListDto> productList = getnewestproductlistbyselleridanddateCall.getProductList();
			List<String> productIdList = productList.stream().map(x -> x.getProductId()).collect(Collectors.toList());
			Logger.verifyEquals(false,productIdList.contains(productId),"验证返回数据直播商品");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}